<template>
    <l-layout class="l-tab-page" v-if="!lr_loadPage" :left="240" v-loading="syncLoading" element-loading-text="拼命同步中...">
        <template #left>
            <l-panel :title="$t('公司信息')" style="padding-right:0;" >
                <el-tree 
                    class="learun-tree"
                    ref="mytree"
                    v-loading="treeLoading" 
                    node-key="value"
                    :data="lr_companyTree" 
                    default-expand-all 
                    :expand-on-click-node="false"  
                    :current-node-key="companyId"
                    @node-click="handleNodeClick">
                    <span class="lr-tree-node"  slot-scope="{ node}">
                        <i class="learun-icon-co"></i>
                        {{ $t(node.label) }}
                    </span>
                </el-tree>
            </l-panel>
        </template>
        <l-panel style="padding-left:0;" >
            <template #toolLeft >
                <div class="l-panel--item" >
                    <el-input :placeholder="$t('please enter关键字')"  @keyup.enter.native="hanleSearch" v-model="searchWord" size="mini" >
                        <el-button @click="hanleSearch" slot="append" icon="el-icon-search"></el-button>
                    </el-input>
                </div>
            </template>
            <template #toolRight >
                <l-tool-btns @click="handleAdd()" >
                    <el-button-group v-if="lr_hasPageAuth('Sync','buttons')">
                        <!-- <el-button type="warning" size="mini" @click="openFrom()" icon="el-icon-refresh">{{ $t("同步") }}</el-button> -->
                    </el-button-group>
                    <l-excel-btns></l-excel-btns>
                </l-tool-btns>
            </template>
            <l-table 
                :columns="lr_getPageColumns(columns)" 
                :dataSource="tableData" 
                :loading="loading" 

                isTree
                rowKey="f_DepartmentId"
                pidKey="f_ParentId"
                >
                <template v-slot:f_EnabledMark="scope" >
                    <el-switch
                        :active-value="1"
                        :inactive-value="0"
                        v-model="scope.row.f_EnabledMark"
                        @change="handleEnableChange(scope.row)"
                        >
                    </el-switch>
                </template>
                <l-table-btns :btns="tableBtns" @click="lr_handleTableBtnClick" ></l-table-btns>
            </l-table>
        </l-panel>

        <l-dialog 
            :height="480"
            :title="formTitle"
            :visible.sync="formVisible"
            @ok="handleSave"
            @close="handleCloseForm"
            @opened="handleOpenedForm"
            >
            <my-form ref="form" ></my-form>       
        </l-dialog>
        <!-- 同步操作 -->
        <l-dialog :title="$t(syncTitle)"
            :visible.sync="syncVisible"
            :height="150"
            :width="400"
            @ok="handleSync"
            >
            <div class="l-from-body">
                <el-form size="small" ref="syncForm" label-width="100px">
                    <el-col :span="24">
                        <el-form-item :label="$t('截止时间')" prop="startTime">
                            <l-date format="yyyy-MM-dd HH:mm:ss" dateType="datetime" :clearable="true"
                            v-model="startTime" :placeholder="$t('please select')"/>
                        </el-form-item>
                    </el-col>
                </el-form>
            </div>
        </l-dialog>
    </l-layout>
</template>

<script>
const api = window.$api.organization.department

import MyForm from './form'
export default {
    components: {
        MyForm
    },
    data () {
        return {
            lr_isPage:true,
            //query
            searchWord:'',
            searchTableData:null,

            loading:false,
            columns: [
                {label:'名称',prop:'f_FullName',minWidth:'150'},
                {label:'编码',prop:'f_EnCode',width:'100'},
                {label:'排序',prop:'f_SortCode',width:'80',align:'center'},
                {label:'负责人',prop:'f_Manager',width:'80',align:'center',dataType:'user'},
                {label:'电话号',prop:'f_OuterPhone',width:'100'},
                {label:'分机号',prop:'f_InnerPhone',width:'70',align:'center'},
            ],
            tableBtns:[
                {prop:'Edit',label:this.$t('Edit'),width:40},
                {prop:'Delete',label:this.$t('Delete'),width:40}
            ],

            treeLoading:false,
            companyId:'',

            formVisible:false,
            formTitle:'',
            formEditRow:null,
            formEdit:false,

            syncLoading:false,
            syncVisible:false,
            syncTitle:this.$t("指定更新截止时间"),
            startTime:""
        }
    },
    computed:{
        list(){
            return this.lr_departments[this.companyId] || []
        },
        tableData(){
            if( this.loading){
                return []
            }
            return this.searchTableData ||this.list
        }
    },
    mounted () {
        this.init()
    },
    methods:{
        async init(){
            this.lr_loadDataItem('DepartmentNature')

            this.treeLoading = true
            await this.lr_loadCompanys()
            if(this.lr_companyTree.length >0){
                this.companyId = this.lr_companyTree[0].f_CompanyId
                if (this.$refs["mytree"]) this.$refs["mytree"].setCurrentKey(this.companyId )
                this.loadTableData()
            }
            
            this.treeLoading = false
        },

        async loadTableData(){
            this.loading = true
            await this.lr_loadDepartments(this.companyId,false)
            this.searchWord = ''
            this.searchTableData = null
            this.loading = false
        },
        hanleSearch(){
            if(this.searchWord){
                this.searchTableData = this.list.filter(item => item.f_FullName.indexOf(this.searchWord) >-1 || item.f_EnCode.indexOf(this.searchWord)>-1)
            }
            else{
                this.searchTableData = null
            }
        },
        handleNodeClick(node) {
            this.loading = true
            this.companyId = node.f_CompanyId
            this.loadTableData()
        },

        handleAdd(){
            if(this.companyId){
                this.formEdit = false
                this.showForm('Add部门')
            }
            else{
                this.$message({
                    type: 'warning',
                    message: this.$t('please select左侧公司!')
                })
            }
        },
        handleEdit($index,row){
            this.formEdit = true
            this.formEditRow = row
            this.showForm('Edit部门')
        },
        handleDelete($index,row){
            this.$confirm(this.$t('This operation will permanently delete the data. Do you want to continue?'), this.$t('Tips'), {
                confirmButtonText: this.$t('confirm'),
                cancelButtonText: this.$t('cancel'),
                type: 'warning'
            }).then(() => {
                api.remove(row.f_DepartmentId).then(()=> {
                    this.$message({
                        type: 'success',
                        message: this.$t('Delete  success')
                    })
                    this.loadTableData()
                }).catch(() => {})
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: this.$t('Delete has been canceled')
                })        
            })
        },
        handleSave(showLoading,hideLoading){
            this.$refs.form.validateForm(()=>{
                showLoading()
                const formData = this.$refs.form.getForm()
                if(this.formEdit){// 修改数据
                    api.update(formData.f_DepartmentId,formData).then(()=> {
                        hideLoading()
                        this.formVisible = false
                        this.$message({
                            type: 'success',
                            message: this.$t('更新成功!')
                        })
                        this.loadTableData()
                    }).catch(() => {
                        hideLoading()
                    })
                }
                else{// Edit data
                    api.add(formData).then(()=> {
                        hideLoading()
                        this.formVisible = false
                        this.$message({
                            type: 'success',
                            message: this.$t('添加成功!')
                        })
                        this.loadTableData()
                    }).catch(() => {
                        hideLoading()
                    })
                }
            })
        },
        handleOpenedForm(){
            if(this.formEdit){
                this.$refs.form.setForm(this.formEditRow)
            }
            else{
                const formData = this.$refs.form.getForm()
                formData.f_CompanyId = this.companyId
                this.$refs.form.setForm(formData)
            }
        },
        handleCloseForm(){
            this.$refs.form.resetForm()
        },
        showForm(text){
            this.formTitle = text
            this.formVisible = true
        },
        //部门同步
        openFrom(){
            this.syncVisible = true
        },
        async handleSync(){
            this.$confirm(this.$t('此操作将开始同步部门信息, 是否继续?'), this.$t('Tips'), {
                confirmButtonText: this.$t('confirm'),
                cancelButtonText: this.$t('cancel'),
                type: 'warning'
            }).then(() => {
                this.syncVisible = false
                this.syncLoading = true
                api.syncData(this.startTime).then(()=> {
                    this.$message({
                        type: 'success',
                        message: this.$t('同步成功!')
                    })
                    this.loadTableData()
                    this.syncLoading = false
                }).catch(() => {})
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: this.$t('已cancel同步')
                })        
            })
        }
    }
}
</script>

